import { defineStore } from "pinia";
import { ref } from "vue";
import { invoke } from "@tauri-apps/api/core";
import type { Todo } from "../types/todo";
import dayjs from "dayjs";

export const useTodoStore = defineStore("todo", () => {
  const todos = ref<Todo[]>([]);

  // 加载待办事项
  async function loadTodos() {
    try {
      const data = await invoke<string>("load_todos");
      todos.value = JSON.parse(data);
    } catch (error) {
      console.error("Failed to load todos:", error);
      todos.value = [];
    }
  }

  // 保存待办事项
  async function saveTodos() {
    try {
      await invoke("save_todos", { data: JSON.stringify(todos.value) });
    } catch (error) {
      console.error("Failed to save todos:", error);
    }
  }

  // 添加待办
  function addTodo(content: string, date?: string) {
    const todo: Todo = {
      id: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      content,
      date: date || dayjs().format("YYYY-MM-DD"),
      completed: false,
      createdAt: Date.now(),
    };
    todos.value.push(todo);
    saveTodos();
    return todo;
  }

  // 更新待办
  function updateTodo(id: string, updates: Partial<Todo>) {
    const index = todos.value.findIndex((t) => t.id === id);
    if (index !== -1) {
      todos.value[index] = { ...todos.value[index], ...updates };
      saveTodos();
    }
  }

  // 切换完成状态
  function toggleComplete(id: string) {
    const todo = todos.value.find((t) => t.id === id);
    if (todo) {
      todo.completed = !todo.completed;
      // 记录完成时间或清除完成时间
      todo.completedAt = todo.completed ? Date.now() : undefined;
      saveTodos();
    }
  }

  // 删除待办
  function deleteTodo(id: string) {
    todos.value = todos.value.filter((t) => t.id !== id);
    saveTodos();
  }

  // 获取指定日期的待办
  function getTodosByDate(date: string) {
    return todos.value.filter((t) => t.date === date);
  }

  // 获取今日待办
  function getTodayTodos() {
    const today = dayjs().format("YYYY-MM-DD");
    return todos.value.filter((t) => t.date === today);
  }

  // 获取所有未完成待办
  function getIncompleteTodos() {
    return todos.value.filter((t) => !t.completed);
  }

  // 设置优先级
  function setPriority(id: string, priority?: "high" | "medium" | "low") {
    const todo = todos.value.find((t) => t.id === id);
    if (todo) {
      todo.priority = priority;
      saveTodos();
    }
  }

  // 循环切换优先级
  function cyclePriority(id: string) {
    const todo = todos.value.find((t) => t.id === id);
    if (todo) {
      const order: Array<"high" | "medium" | "low" | undefined> = [
        undefined,
        "low",
        "medium",
        "high",
      ];
      const current = order.indexOf(todo.priority);
      todo.priority = order[(current + 1) % order.length];
      saveTodos();
    }
  }

  // 获取排序后的待办
  function getSortedTodos(todoList: Todo[]) {
    const priorityOrder: Record<string, number> = {
      high: 0,
      medium: 1,
      low: 2,
      undefined: 3,
    };

    return [...todoList].sort((a, b) => {
      // 1. 完成状态：未完成在前
      if (a.completed !== b.completed) {
        return a.completed ? 1 : -1;
      }

      // 2. 优先级：高 > 中 > 低 > 无
      const aPriority = priorityOrder[a.priority ?? "undefined"];
      const bPriority = priorityOrder[b.priority ?? "undefined"];
      if (aPriority !== bPriority) {
        return aPriority - bPriority;
      }

      // 3. 日期：早的在前
      if (a.date !== b.date) {
        return a.date.localeCompare(b.date);
      }

      // 4. 创建时间：早的在前
      return a.createdAt - b.createdAt;
    });
  }

  return {
    todos,
    loadTodos,
    saveTodos,
    addTodo,
    updateTodo,
    toggleComplete,
    deleteTodo,
    getTodosByDate,
    getTodayTodos,
    getIncompleteTodos,
    setPriority,
    cyclePriority,
    getSortedTodos,
  };
});
